import React, { Component } from 'react';
import { Button, Image, Modal, Form, Input, Radio, Checkbox, Col, Row, InputNumber, Switch, Tooltip, message } from 'antd';
import { SettingOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import GoBack from "@/components/TheGoBack";
import TheUpload from '@/components/TheUpload'
import Calendar from '../components/calendar'
import TheButton from '@/components/TheButton';

import { apiProviderId, apiProviderEdit } from '@/request/callServicer/servicer'
import './style.less'
const { TextArea } = Input;
export default class AuthDetail extends Component {
  formRef = React.createRef()
  constructor(props) {
    super(props)
    this.formRef = React.createRef()
    this.state = {
      infos: {
        providerId: '服务者ID',
        niceName: '昵称',
        accountStatus: '用户状态',
        createTime: '注册时间',
        approvalTime: '审核通过',
        name: '姓名',
        mobile: '手机号',
        wxNumber: '微信号',
        occupationClass: '职业类型',
        serviceRange: '服务范围',
        area: '地区',
        address: "详细地址",
      },
      imgs: {
        idCardFront: '身份证人像面',
        idCardBack: '身份证国徽面',
        zmImages: '芝麻信用截图',
        petImages: '与宠物的合照',
      },
      serviceForm: {

      },
      previewVisible: false,
      providerId: '',
      dataSource: {
        skillImages: ''
      },
      isModalVisible: false,
      mode: 'Y',
      previewImgList: [],
      curServiceDay: [],
      commissionFlag: true,//抽佣比例是否显示
    }
  }
  componentDidMount() {
    this.setState({
      providerId: this.props.match.params.id,
      mode: this.props.match.params.mode || 'view'
    }, () => {
      this.getDetail()
    })

  }
  getDetail = () => {
    const { providerId } = this.state
    apiProviderId({
      providerId
    }).then(res => {
      if (res.code == 0) {
        this.setState({
          dataSource: {
            ...res.data,
            accountStatus: res.data.accountStatus == 1 ? '正常' : '冻结',
            area: res.data.economize + res.data.market + res.data.distinguish
          }
        })
        const { provideType,
          skillImages,
          serviceCommissionJson,
          feedCatStatus, feedDogStatus, bathCatStatus, bathDogStatus, alreadyWithdrawPrice, canWithdrawPrice, waitSettledPrice, alreadySettledPrice,
          serviceTimeDTOList,
          feedCat, feedDog, bathCat, bathDog,
          addressClockIn
        } = res.data
        console.log(alreadyWithdrawPrice, canWithdrawPrice, waitSettledPrice, alreadySettledPrice, 'alreadySettledPrice');
        if (serviceCommissionJson) {
          const { feedCatCommission,
            feedDogCommission,
            bathCatCommission,
            bathDogCommission } = serviceCommissionJson
          const serviceDayTimes = {}, serviceDays = []
          serviceTimeDTOList && serviceTimeDTOList.forEach(item => {
            serviceDayTimes[item.serviceTime] = item.serviceTimeDetail
            serviceDays.push(item.serviceTime)
          })
          let skill = [], isFlag = false //是否显示抽佣比例
          if (provideType === 1) {
            if (feedCat === 0) {
              skill.push('feed-cat')
            }
            if (feedDog === 0) {
              skill.push('feed-dog')
            }
            if (bathCat === 0) {
              skill.push('wash-cat')
            }
            if (bathDog === 0) {
              skill.push('wash-dog')
            }
            isFlag = false
          }
          if (provideType === 2) {
            if (feedCatCommission !== '' && feedCatCommission !== null && feedCatCommission !== undefined) {
              skill.push('feed-cat')
            }
            if (feedDogCommission !== '' && feedDogCommission !== null && feedDogCommission !== undefined) {
              skill.push('feed-dog')
            }
            if (bathCatCommission !== '' && bathCatCommission !== null && bathCatCommission !== undefined) {
              skill.push('wash-cat')
            }
            if (bathDogCommission !== '' && bathDogCommission !== null && bathDogCommission !== undefined) {
              skill.push('wash-dog')
            }
            isFlag = true
          }
          this.formRef.current.setFieldsValue({
            addressClockIn: addressClockIn === 0 ? true : false,
            provideType,
            skillImages,
            feedCatStatus: !feedCatStatus, //0可以接单 1不可以
            feedDogStatus: !feedDogStatus,//0可以接单 1不可以
            bathCatStatus: !bathCatStatus,//0可以接单 1不可以
            bathDogStatus: !bathDogStatus,//0可以接单 1不可以
            feedCatCommission: feedCatCommission === null || undefined || '' ? null : React.$transNum(feedCatCommission, 2, -2),
            feedDogCommission: feedDogCommission === null || undefined || '' ? null : React.$transNum(feedDogCommission, 2, -2),
            bathCatCommission: bathCatCommission === null || undefined || '' ? null : React.$transNum(bathCatCommission, 2, -2),
            bathDogCommission: bathDogCommission === null || undefined || '' ? null : React.$transNum(bathDogCommission, 2, -2),
            alreadyWithdrawPrice: alreadyWithdrawPrice ? React.$transNum(alreadyWithdrawPrice, 2, -2) : 0,
            canWithdrawPrice: canWithdrawPrice ? React.$transNum(canWithdrawPrice, 2, -2) : 0,
            waitSettledPrice: waitSettledPrice ? React.$transNum(waitSettledPrice, 2, -2) : 0,
            alreadySettledPrice: alreadySettledPrice ? React.$transNum(alreadySettledPrice, 2, -2) : 0,
            skill,
            serviceDays,
            serviceDayTimes
          })
          this.setState({ commissionFlag: isFlag })
        }
      }
    })
  }

  checkDay = (day) => {
    const values = this.formRef.current.getFieldValue()
    this.setState({
      curServiceDay: values.serviceDayTimes && values.serviceDayTimes.hasOwnProperty(day) ? values.serviceDayTimes[day] : []
    })
  }
  // 表单字段值更新时触发回调事件
  onValuesChange = async (changedValues) => {
    if ('provideType' in changedValues) {
      //全职不显示抽佣比例输入框
      if (changedValues.provideType === 1) {
        this.setState({ commissionFlag: false })
      }
      if (changedValues.provideType === 2) {
        this.setState({ commissionFlag: true })
      }
      this.formRef.current.setFieldsValue({ skill: [], feedCatCommission: null, feedDogCommission: null, bathCatCommission: null, bathDogCommission: null })
    }
  }

  onFinish = (values) => {
    const { skill, feedCatCommission, bathCatCommission, addressClockIn, bathDogCommission, feedDogCommission, provideType } = values
    let skillNew = [] //
    let outProportion = []
    let scale = false
    // const message = () => {
    //   return new Promise((resolve, reject) => {
    //     React.$confirm({
    //       title: "提醒",
    //       okText: "确定",
    //       type: 'warning',
    //       content: `当前抽佣比例较高，${outProportion.json(',')}超出了40%，抽佣比例越高，平台收益越高，服务者收益越少，确定设置该抽佣比例么？`,
    //       onOk: () => {
    //         resolve('ok')
    //       },
    //       onCancel: () => {
    //         reject('cancel')
    //       }
    //     });
    //   })
    // }
    skillNew = Array.from(new Set(skill))
    if (provideType === 2) {
      if (skillNew.includes('feed-cat')) {
        if (feedCatCommission === null || feedCatCommission === '' || feedCatCommission === undefined) {
          return message.error('喂猫抽佣比例请输入0.00~100之间的值!!')
        } else if (feedCatCommission >= 40.00) {
          outProportion.push(feedCatCommission + '%')
          scale = true
        }
      }
      if (skillNew.includes('feed-dog')) {
        if (feedDogCommission === null || feedDogCommission === '' || feedDogCommission === undefined) {
          return message.error('喂狗抽佣比例请输入0.00~100之间的值!!')
        } else if (feedDogCommission >= 40.00) {
          outProportion.push(feedDogCommission + '%')
          scale = true
        }
      }
      if (skillNew.includes('wash-cat')) {
        if (bathCatCommission === null || bathCatCommission === '' || bathCatCommission === undefined) {
          return message.error('洗猫抽佣比例请输入0.00~100之间的值!!')
        } else if (bathCatCommission >= 40.00) {
          outProportion.push(bathCatCommission + '%')
          scale = true
        }
      }
      if (skillNew.includes('wash-dog')) {
        if (bathDogCommission === null || bathDogCommission === '' || bathDogCommission === undefined) {
          return message.error('洗狗抽佣比例请输入0.00~100之间的值!!')
        } else if (bathDogCommission >= 40.00) {
          outProportion.push(bathDogCommission + '%')
          scale = true
        }
      }
    }
    const { providerId, memberId } = this.state
    const confirm = () => {
      apiProviderEdit({
        providerId,//主键id不能为空
        memberId,//会员Id 加锁用
        provideType,//服务者类型不能为空
        addressClockIn: addressClockIn ? 0 : 1,
        feedCatCommission: skill.includes('feed-cat') ? feedCatCommission * 100 : null,//喂猫抽佣比例 没有勾选默认为空或null
        feedDogCommission: skill.includes('feed-dog') ? feedDogCommission * 100 : null,//喂狗抽佣比例 没有勾选默认为空或null
        bathCatCommission: skill.includes('wash-cat') ? bathCatCommission * 100 : null,//洗狗抽佣比例 没有勾选默认为空或null
        bathDogCommission: skill.includes('wash-dog') ? bathDogCommission * 100 : null,//洗猫抽佣比例 没有勾选默认为空或null
        feedCat: skill.includes('feed-cat') ? 0 : 1,//喂猫 没有勾选默认为空或null 勾选0 未勾选1
        feedDog: skill.includes('feed-dog') ? 0 : 1,//喂狗  没有勾选默认为空或null 勾选0 未勾选1
        bathCat: skill.includes('wash-cat') ? 0 : 1,//洗狗  没有勾选默认为空或null 勾选0 未勾选1
        bathDog: skill.includes('wash-dog') ? 0 : 1,//洗猫  没有勾选默认为空或null 勾选0 未勾选1
      }).then(res => {
        if (res.code == 0) {
          React.$message({ type: 'success', content: `操作成功` })
          this.props.history.goBack()
        }
      })
    }

    if (scale) {
      React.$confirm({
        title: "提醒",
        type: 'warning',
        content: `当前抽佣比例较高，${outProportion.join(',')}超出了40%，抽佣比例越高，平台收益越高，服务者收益越少，确定设置该抽佣比例么？`,
        onOk: async () => {
          confirm()
        },
        onCancel: () => {
          return
        }
      });
    } else {
      confirm()
    }
  }
  KillChange = (e, key) => {
    console.log('Received values of form: ', e, key);
  }
  render() {
    const { infos, imgs, dataSource, isModalVisible, curServiceDay, mode, previewVisible, previewImgList, commissionFlag } = this.state
    return (
      <div className='p-layout-box'>
        <GoBack history={this.props.history} title={"基础信息"} />
        <div className="content" style={{ width: '100%' }}>

          <Form
            name="validate_other"
            ref={this.formRef}
            onFinish={this.onFinish}
            onValuesChange={this.onValuesChange}
          >
            <Row style={{ width: "100%" }}>
              {
                Object.keys(infos).map(key => {
                  return (
                    <Col span={8} className="li">
                      <span className='label'>{infos[key]}：</span>
                      <span className='value'>&nbsp;&nbsp;{infos[key] === '服务范围' ? React.$transNum(dataSource[key], 0, -3) + 'km' : dataSource[key]}</span>
                    </Col>
                  )
                })
              }
            </Row>
            <Form.Item label="位置打卡" name="addressClockIn" valuePropName="checked">
              <Switch ></Switch>
            </Form.Item>
            <Row>
              {
                Object.keys(imgs).map(key => {
                  let imgLength = dataSource[key] ? `(共${dataSource[key].split(',').length}张)` : ''
                  return (
                    <Col span={4} className="li">
                      {/* <div className='label'>{imgs[key]}</div> */}
                      <div className='label'>{imgs[key]}{imgLength}</div>
                      {
                        dataSource[key] ? <div>
                          <Image
                            className='img'
                            src={dataSource[key].split(',')[0]}
                            preview={{
                              visible: false,
                            }}
                            onClick={() => this.setState({
                              previewVisible: true,
                              previewImgList: dataSource[key].split(',')
                            })}
                          />
                        </div> : '无'
                      }
                      {/* {
                        dataSource[key] ? dataSource[key].split(',').map(item => {
                          return <div>
                            <Image
                              className='img'
                              src={item}
                              preview={{
                                visible: false,
                              }}
                              onClick={() => this.setState({
                                previewVisible: true,
                                previewImgList: dataSource[key].split(',')
                              })}
                            />
                          </div>
                        }) : '无'
                      } */}
                    </Col>
                  )
                })
              }
            </Row>
            <div className='module-title'></div>
            <div className='module-title'>
              服务信息
            </div>

            <div style={{ display: 'flex' }}>
              <div>相关证书：</div>
              {
                dataSource.skillImages ? dataSource.skillImages.split(',').map(item => {
                  return <Image
                    className='img'
                    style={{
                      width: 100,
                      height: 100,
                    }}
                    src={item}
                    preview={{
                      visible: false,
                    }}
                    onClick={() => this.setState({
                      previewVisible: true,
                      previewImgList: dataSource['skillImages'].split(',')
                    })}
                  />
                }) : '无'
              }
              {/* {
                dataSource.skillImages.split(',').map(item => {
                  return <Image
                    className='img'
                    style={{
                      width: 100,
                      height: 100,
                    }}
                    src={item}
                    preview={{
                      visible: false,
                    }}
                    onClick={() => this.setState({
                      previewVisible: true,
                      previewImgList: dataSource['skillImages'].split(',')
                    })}
                  />
                })
              } */}
            </div>

            <Form.Item label="类型" name="provideType">
              <Radio.Group disabled={mode == 'view'}>
                <Radio value={1}>全职</Radio>
                <Radio value={2}>兼职</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item label="服务技能" name="skill">
              <Checkbox.Group style={{ width: '100%' }} >
                <Row>
                  <Col span={8}>
                    <Checkbox
                      disabled={mode == 'view'}
                      value="feed-cat"
                      style={{
                        lineHeight: '32px',
                      }}
                    >
                      喂猫
                    </Checkbox>
                    {
                      commissionFlag && <Form.Item label="抽佣比例：" name="feedCatCommission" >
                        <InputNumber disabled={mode == 'view'} min={0} max={100} style={{ width: 100, }} addonAfter={<span>%</span>} />
                      </Form.Item>
                    }
                  </Col>
                  <Col span={8}>
                    <Checkbox
                      value="feed-dog" disabled={mode == 'view'}
                      style={{
                        lineHeight: '32px',
                      }}
                    >
                      喂狗
                    </Checkbox>
                    {
                      commissionFlag &&
                      <Form.Item label="抽佣比例：" name="feedDogCommission" >
                        <InputNumber disabled={mode == 'view'} min={0} max={100} style={{ width: 100, }} addonAfter={<span>%</span>} />
                      </Form.Item>
                    }
                  </Col>
                </Row>
                <Row>
                  <Col span={8}>
                    <Checkbox disabled={mode == 'view'}
                      value="wash-cat"
                      style={{
                        lineHeight: '32px',
                      }}
                    >
                      洗猫
                    </Checkbox>
                    {
                      commissionFlag &&
                      <Form.Item label="抽佣比例：" name="bathCatCommission" >
                        <InputNumber disabled={mode == 'view'} min={0} max={100} style={{ width: 100, }} addonAfter={<span>%</span>} />
                      </Form.Item>
                    }
                  </Col>
                  <Col span={8}>
                    <Checkbox disabled={mode == 'view'}
                      value="wash-dog"
                      style={{
                        lineHeight: '32px',
                      }}
                    >
                      洗狗
                    </Checkbox>
                    {
                      commissionFlag &&
                      <Form.Item label="抽佣比例：" name="bathDogCommission" >
                        <InputNumber disabled={mode == 'view'} min={0} max={100} style={{ width: 100, }} addonAfter={<span>%</span>} />
                      </Form.Item>
                    }
                  </Col>
                </Row>
              </Checkbox.Group>
            </Form.Item>
            <div className='module-title'>
              佣金收益
            </div>
            <Row>
              <Col span={6}>
                <Form.Item
                  shouldUpdate
                >
                  {({ getFieldValue }) => {
                    return <Form.Item label="可提现金额" name="canWithdrawPrice" >
                      <span>{getFieldValue('canWithdrawPrice')}元</span>
                      <Tooltip placement="bottomLeft" title={'可提现金额 = 累计结算金额  减去 已提现到账、提现中且未到账的金额之和'}>
                        &nbsp;&nbsp;<QuestionCircleOutlined />
                      </Tooltip>
                    </Form.Item>
                  }}
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item
                  shouldUpdate
                >
                  {({ getFieldValue }) => {
                    return <Form.Item label="累计提现金额" name="alreadyWithdrawPrice" >
                      <span>{getFieldValue('alreadyWithdrawPrice')}元</span>
                      <Tooltip placement="bottomLeft" title={'所选服务者累计提现到账的金额。'}>
                        &nbsp;&nbsp;<QuestionCircleOutlined />
                      </Tooltip>
                    </Form.Item>
                  }}
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item
                  shouldUpdate
                >
                  {({ getFieldValue }) => {
                    return <Form.Item label="待结算金额" name="waitSettledPrice" >
                      <span>{getFieldValue('waitSettledPrice')}元</span>
                      <Tooltip placement="bottomLeft" title={'今日0点及之后所有未结算（状态为待服务、服务中、已完成）服务订单的金额之和+消费者有责待结算退款金额之和'}>
                        &nbsp;&nbsp;<QuestionCircleOutlined />
                      </Tooltip>
                    </Form.Item>
                  }}
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item
                  shouldUpdate
                >
                  {({ getFieldValue }) => {
                    return <Form.Item label="累计结算金额" name="alreadySettledPrice" >
                      <span>{getFieldValue('alreadySettledPrice')}元</span>
                      <Tooltip placement="bottomLeft" title={'该服务者服务订单行结算状态为已结算的服务者所得金额之和'}>
                        &nbsp;&nbsp;<QuestionCircleOutlined />
                      </Tooltip>
                    </Form.Item>
                  }}
                </Form.Item>
              </Col>

            </Row>
            <div className='module-title'>
              接单设置
            </div>
            <Form.Item label="接单状态"
              noStyle
            >
              <Row>
                <Col span={4}>
                  <Form.Item label="喂猫" name="feedCatStatus" valuePropName="checked">
                    <Switch disabled></Switch>
                  </Form.Item>
                </Col>
                <Col span={4}>
                  <Form.Item label="喂狗" name="feedDogStatus" valuePropName="checked">
                    <Switch disabled></Switch>
                  </Form.Item>
                </Col>
                <Col span={4}>
                  <Form.Item label="洗猫" name="bathCatStatus" valuePropName="checked">
                    <Switch disabled ></Switch>
                  </Form.Item>
                </Col>
                <Col span={4}>
                  <Form.Item label="洗狗" name="bathDogStatus" valuePropName="checked">
                    <Switch disabled></Switch>
                  </Form.Item></Col>
              </Row>
            </Form.Item>
            <Form.Item shouldUpdate={(prevValues, currentValues) => prevValues.serviceDays !== currentValues.serviceDays}>
              {
                ({ getFieldValue }) => {
                  return <Row>
                    <Col>
                      <Form.Item label="接单日期" >
                        <Calendar lightHighDays={getFieldValue('serviceDays')} checkDay={this.checkDay}></Calendar>
                      </Form.Item>
                    </Col>
                    {
                      curServiceDay.length > 0 && <Col style={{ width: '50%' }}>
                        <Form.Item label="接单时间段" style={{ width: '100%' }}>
                          <div style={{ maxWidth: '100%', display: 'flex', flexWrap: 'wrap' }}>
                            {
                              curServiceDay.map(item => {
                                return <div className='times'>{item}</div>
                              })
                            }
                          </div>
                        </Form.Item>
                      </Col>
                    }
                    {/* {
                      curServiceDay.length > 0 && <Col  >
                        <Form.Item label="接单时间段" >
                          <div style={{ maxWidth: '100%', display: 'flex', flexWrap: 'wrap' }}>
                            {
                              curServiceDay.map(item => {
                                return <div className='times'>{item}</div>
                              })
                            }
                          </div>
                        </Form.Item>
                      </Col>
                    } */}
                  </Row>
                }
              }
            </Form.Item>
            <Form.Item
              wrapperCol={{
                span: 12,
                offset: 6,
              }}
            >
              <Button style={{ marginRight: 20 }} onClick={this.props.history.goBack}>
                取消
              </Button>
              {
                mode != 'view' && <TheButton haspermi={['call:servicerList:save']} type="primary" htmlType="submit">
                  保存
                </TheButton>
              }

            </Form.Item>
          </Form>
        </div>
        <div
          style={{
            display: 'none',
          }}
        >
          <Image.PreviewGroup
            preview={{
              visible: previewVisible,
              onVisibleChange: (vis) => this.setState({
                previewVisible: vis
              }),
            }}
          >
            {
              previewImgList.map(item => {
                return <Image src={item} />
              })
            }

          </Image.PreviewGroup>
        </div>
      </div >
    );
  }
}
